package com.itheima.web; /**
 * @author tongchen
 * @create 2022-12-01 10:59
 */

import com.itheima.pojo.User;
import com.itheima.service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    //创建service对象
     UserService userService=new UserService();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取前端数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User user = userService.select(username, password);
        if(user!=null){
            //登录成功
            //储存数据
            String remember = request.getParameter("remember");
            if("1".equals(remember)){
                Cookie c_username = new Cookie("username",username);
                Cookie c_password = new Cookie("password",password);
                c_username.setMaxAge(60*60*24*7);
                c_password.setMaxAge(60*60*24*7);
                //发送cookie
                response.addCookie(c_username);
                response.addCookie(c_password);
            }

            //创建session
            HttpSession session = request.getSession();
            session.setAttribute("user",user);
            //进行跳转访问
            String contextPath = request.getContextPath();
            response.sendRedirect(contextPath+"/selectAllServlet");
        }else {
            //登陆失败
            //跳转到失败页面
            request.setAttribute("msg","用户名或密码错误，登陆失败");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
